package demo.deep;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.util.Date;
import java.util.function.Consumer;

@RequestMapping(value = "flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@RestController
public class SpringSse {

    @RequestMapping("stream")
    public Flux<String> stream() {
        System.out.println("1");
        return Flux.interval(Duration.ofSeconds(1)).map(s -> new Date().toString());
//        return Flux.just(new Date().toString()).delayElements(Duration.ofSeconds(1));
    }

    public static void main(String[] args) throws InterruptedException {

        //创建了一个数据流 并设置1秒的延迟
        Flux<String> flux = Flux.just("Hello", "World").delayElements(Duration.ofSeconds(1));

        //获取到流中的元素 并进行处理
        Flux<String> map = flux.map(String::toLowerCase);

        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };

        map.subscribe(consumer);

        Thread.sleep(4000);
    }
}
